<?php

namespace common\services\order;

use api\models\user\User;
use common\models\order\OrderModel;
use common\models\order\OrderGoodsModel;
use common\models\order\OrderExtraModel;
use common\services\goods\GoodsStockService;
/**
 * Desc 订单管理服务类
 * @author WMX
 */
class OrderCommonService
{

    // 获取订单列表
    public static function getUnionAll($condition = [], $page = 1, $page_size = 20)
    {
        $query = OrderModel::find()->alias('o')->leftJoin('user u', 'u.id=o.user_id');
        list($offset, $limit) = \common\tools\Util::getLimit($page, $page_size);
        if ($condition) {
            $query->where($condition);
        }
        $query->select(['o.*','u.phone as user_phone']);
        $list['total'] = intval($query->count());
        $query->offset($offset)->limit($limit);
        $list['list'] = $query->asArray()->all();
        
        $order_sns = array_column($list['list'], 'order_sn');
        $order_goods = OrderGoodsModel::getAll(['in', 'order_sn', $order_sns]);
        $order_addr = OrderExtraModel::getAll(['in', 'order_sn', $order_sns]);

        $order_goods_data = [];
        foreach ($order_goods as $val) {
            $order_goods_data[$val['order_sn']][] = $val;
        }
        $order_addr_data = [];
        foreach ($order_addr as $val) {
            $order_addr_data[$val['order_sn']][] = $val;
        }

        foreach ($list['list'] as &$value) {
            $value['state_name'] = OrderModel::$state[$value['state']] ?? '';
            $value['pay_name'] = OrderModel::$pay_way[$value['pay_way']] ?? '';
            $value['addr_info'] = $order_addr_data[$value['order_sn']] ?? [];
            $value['goods_list'] = $order_goods_data[$value['order_sn']] ?? [];
            $value['order_goods_count'] = 0;
            foreach ($order_goods_data[$value['order_sn']] as $goods_item) {
                $value['order_goods_count'] += $goods_item['count'];
            }
        }

        return $list;
    }


    // 获取订单详情
    public static function getOrderDetail($order_sn)
    {
        $order_info = OrderModel::getDataOne(['order_sn' => $order_sn]);
        $user_info = User::getDataOne(['id'=> $order_info['user_id']]);
        $order_info['user_phone'] =  $user_info['phone'];
        $order_info['goods_list'] = OrderGoodsModel::getAll(['order_sn' => $order_sn]);
        $order_info['addr_info'] = OrderExtraModel::getDataOne(['order_sn' => $order_sn]);
        $order_info['state_name'] = OrderModel::$state[$order_info['state']] ?? '';
        $order_info['pay_name'] = OrderModel::$pay_way[$order_info['pay_way']] ?? '';
        $order_info['order_goods_count'] = 0;
        $order_info['total_discount_amount'] = $order_info['discount_amount'] + $order_info['manjian_amount'] + $order_info['coupon_amount'];
        foreach ($order_info['goods_list'] as $goods_item) {
            $order_info['order_goods_count'] += $goods_item['count'];
        }
        return $order_info;
    }


    /**
     * 订单取消-库存释放
     * @param string $order_sn 订单号
     * @param string $desc 备注
     * **/
    public static function cancel($order_sn)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            if(empty(\Yii::$app->cache->add('OPEN_ORDER_CANCEL_'.$order_sn, 1,10))){
                throw new \Exception('业务处理中，请勿频繁操作');
            }
            $order = OrderModel::find()->where(['order_sn'=>$order_sn])->one();
            if(empty($order)){
                throw new \Exception('订单信息异常');
            }
            if($order->state != OrderModel::STATE_WAIT_PAY){
                throw new \Exception('该状态订单无法取消');
            }
            $order->state = OrderModel::STATE_CANCEL;
            $order->cancel_time = date('Y-m-d H:i:s');
            if(empty($order->save())){
                throw new \Exception('订单取消异常');
            }
            $goods = OrderGoodsModel::getAll(['order_sn'=>$order_sn]);
            // 库存释放
            $stock = GoodsStockService::release(
                $goods
            );
            if($stock['code'] == 201){
                throw new \Exception($stock['message']);
            }
            //取消券回滚-跨境
            if($order['coupon_amount'] > 0){
                \api\services\active\ActiveCouponService::rollback($order_sn);
            }

            $transaction->commit();
            
            return 'success';
        } catch (\Exception $exc) {
             $transaction->rollBack();
            return $exc->getMessage();
        }
    }
}
